<template>
  <el-container class="column-page">
    <el-aside width="160px">
      <data-cell center right @click="setDefaultActive(0)" :active="where.cate_id===0">
        全部
      </data-cell>
      <data-cell center v-for="(item,index) in classify" @click="setDefaultActive(item.id)" :key="index" hover-left :active="where.cate_id===item.id">
        {{ item.name }}
        <template #right>
          <el-space class="app-vertical-middle">
            <svg-icon @click.stop="UpdatedResourcesCate(item.id)" color="var(--el-color-primary)" :size="16" name="edit"/>
            <svg-icon @click.stop="deleteResourcesCate(item.id)" color="#ff0000" :size="16" name="delete"/>
          </el-space>
        </template>
      </data-cell>
      <data-cell center>
        <svg-icon class="app-vertical-middle" color="var(--el-color-primary)" @click="createdResourcesCate" :size="16" name="push"></svg-icon>
      </data-cell>
    </el-aside>
    <el-main>
      <data-card title="资源管理">
        <template #right>
          <el-space spacer="|">
            <el-input size="small" class="app-width-p220" placeholder="资源名称" v-model.trim="where.name" maxlength="30">
              <template #append>
                <el-button size="small" @click="getRequestData({page:1,size:pagination.size})">搜索</el-button>
              </template>
            </el-input>
            <el-button size="small" @click="openUpload" type="success">上传</el-button>
            <el-button size="small" v-if="_primarys.length" @click="moveCate(_primarys)" type="warning">移动</el-button>
            <confirm-button v-if="_primarys.length>0" size="small" type="danger" @confirm="DeleteData(_primarys)" title="确定要删除选中数据吗">
              删除
            </confirm-button>
          </el-space>
        </template>
        <el-tabs v-model="where.type" @tab-change="typeChange">
          <el-tab-pane v-for="item in ResType" :label="item.label" :name="item.value"></el-tab-pane>
        </el-tabs>
        <app-table height="calc(var(--ach) - 166px)" @choice="TabelChoice" :loading :columns :pagination :data="list" @reload="getRequestData">
          <template #action="{ row }">
            <el-space>
              <operate-link @tap="ActionHandle('update',row)">编辑</operate-link>
              <operate-link @tap="ActionHandle('remove',row)" confirm="确定要删除所选资源吗?">删除</operate-link>
            </el-space>
          </template>
          <template #is_show="{ row }">
            <el-link type="success" v-if="row.is_show">是</el-link>
            <el-link type="danger" v-else>否</el-link>
          </template>
          <template #drive="{ row }">
            <el-link type="primary" v-if="row.drive==='local'">本机储存</el-link>
            <el-link type="success" v-else-if="row.drive==='oss'"> 阿里云OSS</el-link>
            <el-link type="danger" v-else-if="row.drive==='cos'">腾讯云COS</el-link>
          </template>
          <template #url="{ row }">
            <el-tag v-if="row.url" v-copy="row.url" class="app-tap" :title="row.url">复制</el-tag>
          </template>
          <template #image="{ row }">
            <el-image class="app-width-p20 app-height-p20" loading="lazy" lazy preview-teleported v-if="row.url" :preview-src-list="[row.url]" :src="row.url"/>
          </template>
          <template #size="{ row }">
            <file-size :size="row.size"/>
          </template>
        </app-table>
      </data-card>
    </el-main>
  </el-container>
</template>
<script lang="ts">
import {defineComponent, ref, onActivated, h, defineAsyncComponent, computed} from "vue"
import {createdResourcesCateApi, getResourcesCateListApi, updatedResourcesCateApi, deleteResourcesCateApi, getResourcesDataApi, renameResourcesApi, removeResourcesApi, getUploaderConfigureApi} from "@/api/resources"
import {usePopupComponent, usePopupForm} from "@/components/FunctionComponents"
import {getResCateType} from "@/components/ResourceLibrary/config"
import {useConfirmDialog} from "@/hooks/DialogMsg"
import {useHttpPagingResult} from "@/hooks/http";
import {TableColumn} from "@/components/AppTable/TableType";
import {ElMessage, ElMessageBox} from "element-plus";
import LibraryConfig from "@/components/ResourceLibrary/config"
import {useTableChoice} from "@/components/AppTable/TableHook";

export default defineComponent({
  setup() {
    /**
     * 表格选择工具
     */
    const {TabelChoice, _primarys} = useTableChoice<number>()

    /**
     * 资源分类
     */
    const classify = ref<{ id: number, name: string }[]>([])//资源分类

    /**
     * 获取资源类被
     */
    const ResType = getResCateType()
    const where = ref({
      type: ResType[0].value,
      name: '',
      cate_id: 0
    })

    /**
     * 获取资源分类
     */
    async function getClassifyData() {
      const {code, data} = await getResourcesCateListApi({type: where.value.type})
      if (code === 200) {
        classify.value = data
      }
    }


    /**
     * 设置分类
     */
    function setDefaultActive(id: number) {
      where.value.cate_id = id
      getRequestData({page: 1, size: pagination.size})
    }

    /**
     * 类型切换
     */
    function typeChange() {
      getRequestData({page: 1, size: pagination.size})
      getClassifyData()
    }


    /**
     * 打开上传面板
     */
    function openUpload() {
      let config = LibraryConfig[where.value.type]
      getUploaderConfigureApi(where.value.type).then(result => {
        const component: any = h(defineAsyncComponent((): any => import("@/components/ResourceLibrary/Upload/ChoiceResource.vue")), {
          type: where.value.type,
          conf: config,
          classify: classify.value,
          uploadConf: result.data,
          onClose: () => getRequestData({page: pagination.page, size: pagination.size})
        })
        usePopupComponent(`上传${config.name}`, component, "680px")
      })
    }


    /**
     * 创建菜单分类
     */
    function createdResourcesCate() {
      usePopupForm({
        api: createdResourcesCateApi,
        query: {type: where.value.type},
        width: '420px',
        successTips: false,
        onSuccess: getClassifyData
      })
    }


    /**
     * 编辑菜单分类
     * @param id
     * @constructor
     */
    function UpdatedResourcesCate(id: number) {
      usePopupForm({
        api: updatedResourcesCateApi,
        query: {id},
        width: '420px',
        successTips: false,
        onSuccess: getClassifyData
      })
    }


    /**
     * 删除资源分类
     * @param id
     */
    async function deleteResourcesCate(id: number) {
      let state = await useConfirmDialog("确定要删除所选分类吗?")
      if (state === false) {
        return;
      }
      let {code} = await deleteResourcesCateApi({id: id})
      if (code === 200) {
        if (where.value.cate_id === id) {
          where.value.cate_id = 0
        }
        await getClassifyData()
      }
    }

    /**
     * 文件资源数据获取
     */
    const {pagination, list, loading, getRequestData} = useHttpPagingResult(function (query) {
      return getResourcesDataApi({
        ...query, ...where.value, cate_id: where.value.cate_id ? where.value.cate_id : ''
      })
    })


    /**
     * 列配置
     */
    const columns = computed<TableColumn[]>(() => {
      var columns: TableColumn[] = [
        {type: "selection"},
        {prop: "id", label: "id", fixed: "left", minWidth: 100},
        {prop: "name", label: "文件名", fixed: "left", minWidth: 250, showOverflowTooltip: true},
        {type: "action", label: "操作", fixed: "left", align: 'center', width: 110},
        {prop: "is_show", label: "资源库", minWidth: 100},
        {prop: "drive", label: "储存驱动", minWidth: 100},
        {prop: "size", label: "文件大小", minWidth: 100},
        {prop: "time", label: "上传时间", type: "timestramp", minWidth: 165}
      ]
      if (where.value.type === 'image') {
        columns.splice(3, 0, {prop: "image", label: "图片预览", type: "image", minWidth: 100})
      }else{
        columns.splice(3, 0, {prop: "url", label: "资源地址", minWidth: 100})
      }
      return columns
    })


    /**
     * 删除资源
     * @constructor
     */
    function DeleteData(value: number[]) {
      removeResourcesApi(value).then(result => {
        if (result.code === 200) {
          getRequestData({page: pagination.page, size: pagination.size})
        }
      })
    }


    /**
     * 移动分类
     */
    function moveCate(id: number[]) {
      const component = h(defineAsyncComponent((): any => import("@/components/ResourceLibrary/MoveCate.vue")), {
        type: where.value.type,
        id: id,
        onSuccess: () => getRequestData({page: pagination.page, size: pagination.size})
      })
      usePopupComponent('移动资源', component, '360px')
    }


    /**
     * 操作
     * @param action
     * @param res
     * @constructor
     */
    function ActionHandle(action: string, res: any) {
      if (action === 'remove') {
        DeleteData([res.id])
      } else if (action === 'update') {
        ElMessageBox.prompt('请输入新的资源名称', '资源重命名', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          inputValue: res.name,
          inputPattern: /^[\S]{1,40}$/,
          inputErrorMessage: '请输入1-40个字的新名称，不能含有空白字符',
        }).then(({value}) => {
          if (value === res.name) {
            ElMessage({type: "success", message: '资源名称已修改'})
          } else {
            renameResourcesApi({id: res.id, name: value}).then(result => {
              if (result.code === 200) {
                getRequestData({page: pagination.page, size: pagination.size})
              }
            })
          }
        }).catch(() => {
          ElMessage({type: "info", message: '操作已取消'})
        })
      }
    }

    onActivated(() => {
      getClassifyData()
    })

    return {
      where,
      classify,
      ResType,
      setDefaultActive,
      createdResourcesCate,
      UpdatedResourcesCate,
      deleteResourcesCate,
      list,
      DeleteData,
      moveCate,
      columns,
      pagination,
      getRequestData,
      ActionHandle,
      loading,
      typeChange,
      openUpload,
      TabelChoice,
      _primarys
    }
  }
})
</script>
<style lang="scss" scoped>
@use "@/apps/admin/assets/style/column-page.scss";
</style>